//
//  Camera.swift
//  WatermarkCamera
//
//  Created by AxcLogo on 4/7/2024.
//

import UIKit
import Foundation
import AxcBedrock
import AVFoundation
import CoreGraphics

// MARK: - [Camera.Config]

extension Camera {
    struct Config {
        // 默认配置

        static var defaultConfig: Config { return .init() }

        // 分辨率

        var sessionPreset: AVCaptureSession.Preset = .high

        // 相机摄像头

        var cameraPosition: AVCaptureDevice.Position = .back

        // 输出图片方向

        var outputImageOrientation: UIInterfaceOrientation = .portrait
    }
}

// MARK: - [Camera]

typealias GPUFilter = (GPUImageOutput & GPUImageInput)

// MARK: - [Camera.OBKeyPath]

extension Camera {
    enum OBKeyPath: String, CaseIterable {
        case isAdjustingFocus = "adjustingFocus"
    }
}

// MARK: - [Camera]

class Camera: NSObject {
    // Lifecycle

    /// 实例化
    init(config: Config = .defaultConfig) {
        super.init()

        self.config = config

        _config()
    }

    deinit {
//        gpuCamera.inputCamera.removeObserver(self, forKeyPath: OBKeyPath.isAdjustingFocus.rawValue)
    }

    // Open

    /// 配置
    var config: Config = .defaultConfig

    /// 摄像头即将切换
    var willRotateCameraBlock: AxcBlock.OneParam<Camera.Position>?

    /// 摄像头已经完成切换
    var didRotateCameraBlock: AxcBlock.OneParam<Camera.Position>?

    /// 对焦事件回调
    var adjustingFocusBlock: AxcBlock.OneParam<Bool>?

    /// 捕获照片是否完成
    var capturePhotoFinish: Bool = true

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        guard let keyPath = keyPath,

              let caseKeyPath: OBKeyPath = .init(rawValue: keyPath) else { return }

        switch caseKeyPath {
        case .isAdjustingFocus: // 对焦事件回调

            let isAdjustingFocus = gpuCamera.inputCamera.isAdjustingFocus

            adjustingFocusBlock?(isAdjustingFocus)
        }
    }

    // Internal

    /// GPUImage相机
    lazy var gpuCamera: GPUImageStillCamera = {
        let camera = GPUImageStillCamera(sessionPreset: config.sessionPreset.rawValue,

                                         cameraPosition: config.cameraPosition)!

        camera.outputImageOrientation = config.outputImageOrientation

        camera.horizontallyMirrorFrontFacingCamera = true

        camera.delegate = self

        return camera
    }()

    func _config() {
//        gpuCamera.inputCamera.addObserver(self, forKeyPath: OBKeyPath.isAdjustingFocus.rawValue, options: .new, context: nil)
    }
    
    
}

// MARK: GPUImageVideoCameraDelegate

extension Camera: GPUImageVideoCameraDelegate {
    func willOutputSampleBuffer(_ sampleBuffer: CMSampleBuffer!) { }
}
